import os
from PyQt6.QtWidgets import QDialog, QVBoxLayout, QTextEdit, QPushButton, QMessageBox

import Global


class CardManagerDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("卡号管理")
        self.resize(400, 300)
        
        # 创建布局
        layout = QVBoxLayout(self)

        # 添加编辑框
        self.text_edit = QTextEdit(self)
        self.text_edit.setLineWrapMode(QTextEdit.LineWrapMode.NoWrap)
        layout.addWidget(self.text_edit)
        
        # 添加保存按钮
        self.save_button = QPushButton("保存", self)
        self.save_button.clicked.connect(self.save_data)
        layout.addWidget(self.save_button)
        
        # 初始化时加载 card.txt 文件内容
        self.load_data()
    
    def load_data(self):
        # 检查 card.txt 文件是否存在
        if os.path.exists("card.txt"):
            with open("card.txt", "r", encoding="utf-8") as file:
                data = file.read()
                self.text_edit.setPlainText(data)
    
    def save_data(self):
        # 保存数据的逻辑
        data = self.text_edit.toPlainText()
        # 将数据写入 card.txt 文件
        with open("card.txt", "w", encoding="utf-8") as file:
            file.write(data)
        Global.mainWindow.init_card_data()
        QMessageBox.information(self, "提示", "数据已保存")